package com.fanxl.flink.project.app;

import com.alibaba.fastjson.JSON;
import com.fanxl.flink.project.domain.Access;
import com.fanxl.flink.project.domain.EventCategoryProductCount;
import com.fanxl.flink.project.udf.BoundedOutOfOrdernessGenerator;
import com.fanxl.flink.project.udf.GaoDeLocationMapFunction;
import com.fanxl.flink.project.udf.TopNAggFunction;
import com.fanxl.flink.project.udf.TopNWindowFunction;
import org.apache.commons.compress.utils.Lists;
import org.apache.flink.api.common.eventtime.WatermarkGenerator;
import org.apache.flink.api.common.eventtime.WatermarkGeneratorSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.runtime.operators.util.AssignerWithPeriodicWatermarksAdapter;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @description:
 * @author: fanxiaole
 * @date: 2022/3/20 22:01
 */
public class TopNAppV1 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> dataStreamSource = env.readTextFile("data/access.json");
        SingleOutputStreamOperator<Access> cleanStream = dataStreamSource.map(new MapFunction<String, Access>() {
            @Override
            public Access map(String value) throws Exception {
                try {
                    return JSON.parseObject(value, Access.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        })
        .filter(Objects::nonNull)
        .filter(x -> x.getProduct() != null)
        // 设置水位线 解决延迟数据 延迟10秒
        .assignTimestampsAndWatermarks(
                WatermarkStrategy.<Access>forBoundedOutOfOrderness(Duration.ofSeconds(10))
                        .withTimestampAssigner((event, timestamp) -> event.getTime()))
        .filter(x -> !"startUp".equals(x.getEvent()));

        WindowedStream<Access, Tuple3<String, String, String>, TimeWindow> windowedStream = cleanStream
        // 按事件 分类 商品进行分组
        .keyBy(new KeySelector<Access, Tuple3<String, String, String>>() {
            @Override
            public Tuple3<String, String, String> getKey(Access value) throws Exception {
                return Tuple3.of(value.event, value.product.category, value.product.name);
            }
        })
        // 设置滑动窗口 窗口大小5分组 每隔1分组滑动一次
        .window(SlidingEventTimeWindows.of(Time.minutes(5), Time.minutes(1)));

        // 001 005  1  2 3  2 3 4  5  5
        // 002 007  1 5 6
        // 003 008 11

        // 001 005 pay 手机 小米
        // 001 005 pay 汽车 比亚迪
        // 002 007 car 手机 小米
        SingleOutputStreamOperator<EventCategoryProductCount> aggStream = windowedStream
        .aggregate(new TopNAggFunction(), new TopNWindowFunction());

//        aggStream.print();
        // 按 事件 分类 窗口时间进行分组
        aggStream.keyBy(new KeySelector<EventCategoryProductCount, Tuple4<String, String, Long, Long>>() {
            @Override
            public Tuple4<String, String, Long, Long> getKey(EventCategoryProductCount value) throws Exception {
                return Tuple4.of(value.event, value.category, value.start, value.end);
            }
        })
        .process(new KeyedProcessFunction<Tuple4<String, String, Long, Long>, EventCategoryProductCount, List<EventCategoryProductCount>>() {

            private transient ListState<EventCategoryProductCount> listState;

            @Override
            public void open(Configuration parameters) throws Exception {
                listState = getRuntimeContext().getListState(new ListStateDescriptor<EventCategoryProductCount>("cnc-count", EventCategoryProductCount.class));
            }

            @Override
            public void processElement(EventCategoryProductCount value, Context ctx, Collector<List<EventCategoryProductCount>> out) throws Exception {
                listState.add(value);
                // 注册定时器
                ctx.timerService().registerEventTimeTimer(value.end + 1);
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<List<EventCategoryProductCount>> out) throws Exception {
                // 获取窗口内分组的所有数据
                ArrayList<EventCategoryProductCount> list = Lists.newArrayList(listState.get().iterator());
                // 降序排序
                list.sort((x, y) -> Long.compare(y.count, x.count));
                ArrayList<EventCategoryProductCount> sorted = new ArrayList<>();
                // 取前3条
                for (int i =0; i < Math.min(3, list.size()); i++) {
                    sorted.add(list.get(i));
                }
                out.collect(sorted);
            }
        })
        .print();
        env.execute("TopNAppV1");
    }

}
